<?php

namespace app\common\model\system;

use app\common\model\BaseModel;
use think\db\exception\DbException;
use think\Exception;

//版本表
class SystemVersionModel extends BaseModel
{

    protected $name = 'system_version';
    //场景(0:安卓,1:IOS,2:微信,3:电脑端,4:小程序,9:H5)
    protected array $scene = [ 0 => '安卓' , 1 => 'IOS' , 2 => '微信' , 3 => '电脑端', 4 => '小程序' , 9 => 'H5'];
   //0:未生效,1:已生效
    protected array $effect = [ 0 => '未生效' , 1 => '已生效'];

    /**
     * 分页列表
     * @param array $where
     * @throws DbException
     */
    public  function  versionPage($where = [], $page = 1, $page_size = 30)
    {
       return $this->db()->where($where)->field('id,app_name,version,upgrade_url,install_url,is_force,is_transit,create_time,update_time,description,
              scene,scene as scene_name,is_effect,is_effect as effect_name')
            ->withAttr([
                'scene_name' => function(int $v){return $this->scene[$v]?: '未知';},
                'effect_name' => function(int $v){return $this->effect[$v] ?: '未知';}
        ])
        ->paginate(['page' => $page, 'list_rows' => $page_size]);
    }

    /**
     * 修改状态
     */
    public function  versionEditEffect($where , $is_effect){
        return   $this->db()->where($where)->update(['is_effect' => $is_effect]);
    }

    /**
     * 详情
     */
    public function  versionInfo($where = []){
          return   $this->db()->where($where)->order('create_time desc')
              ->field('id,app_name,version,upgrade_url,install_url,is_force,is_transit,create_time,description,
              scene,scene as scene_name,is_effect,is_effect as effect_name')
              ->withAttr([
                  'scene_name' => function(int $v){return $this->scene[$v]?: '未知';},
                  'effect_name' => function(int $v){return $this->effect[$v] ?: '未知';}
              ])->find();

    }

    /**
     * 添加
     */
    public function  versionSave($data = []){

        $where = [];
        if (!empty($data['id'])){
            $where[] = ['id', '<>' , $data['id']];
        }
        //版本号不能重复
        if ($this->db()->where($where)->where([ 'version' => $data['version'] , 'app_name' => $data['app_name']])
                ->count('id') > 0){
            throw new Exception('版本号重复', API_ERROR);
        }
        if (empty($data['id'])) {
            unset($data['id']);
            $res = $this->db()->insertGetId($data);
            if ($res) {
                put_version($data['app_name'],$data['version']);
            }
            return  $res;
        }

        $res = $this->db()->where('id', $data['id'])->update($data);
        if ($res) {
            put_version($data['app_name'],$data['version']);
        }
        return  $res;
    }

}